import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    book: {},
    cart: []
  },
  mutations: {
    addBook(state, bk) {//往购物车中添加商品
      let index = -1;
      for (let i = 0; i < state.cart.length; i++) {
        if (bk.id === state.cart[i].id) {
          index = i;
          break;
        }
      }
      if (index >= 0) {
        if(bk.pnum>state.cart[index].number){
          state.cart[index].number++;
          state.cart[index].lineTotal += bk.price;
        }
        
      } else {
        bk['number'] = 1;
        bk['lineTotal'] = bk.price;
        if(bk.pnum>0){state.cart.push(bk);}
      }
    },
    delBook(state, index) {
      state.cart.splice(index, 1);
    },
    refresh(state, index) {
      //事件一小计发生变化 事件二删除index元素又插入index元素，触发刷新机制
      let book = state.cart[index];
      book.lineTotal = book.number * book.price;
      state.cart.splice(index, 1, book);
    }
  },
  actions: {
    addBook(context, bk) {
      context.commit('addBook', bk)
    },
    delBook(context, index) {
      context.commit('delBook', index)
    }
  },
  getters: {
    getCartNumberById(state){
      return function(id){
        let index=-1
        for (let i = 0; i < state.cart.length; i++) {
         if (id === state.cart[i].id) {
           index = i;
           break;
         }
       }
       if(index>=0){
         return state.cart[index].number;
       }else{
         return 0;
       }
      }
      
    
    },
    // 总价
    totalPrice(state) {
      var price_total = 0;
      for (var i = 0; i < state.cart.length; i++) {
        price_total += state.cart[i].price * state.cart[i].number;
      }
      return price_total;
    },
    // 总数
    totalNumber(state) {
      var number_total = 0;
      for (var i = 0; i < state.cart.length; i++) {
        number_total += state.cart[i].number;
      }
      return number_total;
    },
  },
  
  modules: {
  }
})
